package com.billy.ohos.swipe.demo;

import com.billy.ohos.swipe.SmartSwipeRefresh;
import com.billy.ohos.swipe.SmartSwipeWrapper;
import com.billy.ohos.swipe.SwipeConsumer;
import com.billy.ohos.swipe.demo.consumer.ImageViewerAbility;
import com.billy.ohos.swipe.demo.util.ConsumeListContainer;
import com.billy.ohos.swipe.internal.LogUtil;
import com.ryan.ohos.extension.event.interfaces.ComponentParentHack;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * base ability
 *
 * @author billy.qi
 */
public abstract class BaseRecyclerViewAbility extends BaseAbility {
    public SmartSwipeRefresh smartSwipeRefresh;
    public SwipeConsumer itemConsumer;
    public SwipeConsumer swipeConsumerView;
    protected ConsumeListContainer recyclerView;
    protected RecyclerAdapter adapter;
    // private boolean autoScrollitem = true;

    String[] names;
    String[] messages;
    private AtomicInteger idMaker = new AtomicInteger(0);


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer parse = (ComponentContainer) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_ability_base_recycler_view, null, false);
        super.setUIContent(parse);
        recyclerView = (ConsumeListContainer) findComponentById(ResourceTable.Id_recyclerView);

        adapter = new RecyclerAdapter(getInitData());
        recyclerView.setItemProvider(adapter);
        recyclerView.setLongClickable(false);
    }

    private void handleHorizental(boolean isLeft) {
//        if (autoScrollitem) {
//            if (itemConsumer != null) {
//                if (isLeft) {
//                    itemConsumer.smoothLeftOpen();
//                } else {
//                    itemConsumer.smoothRightOpen();
//                }
//            }
//            autoScrollitem = false;
//        }
    }

    private void handleVetical(boolean isPullDown, List<Data> list) {
        LogUtil.loge("NestedListContainer", " flaView  NestedListContainer ======222222isPullDown" + isPullDown);
        if (isPullDown) {
            if (recyclerView.getFirstVisibleItemPosition() == 0) {
                if (smartSwipeRefresh != null) {
                    smartSwipeRefresh.getSwipeConsumer().lockAllDirections();
                    smartSwipeRefresh.startRefresh();
                }
                if (swipeConsumerView != null) {
                    swipeConsumerView.lockAllDirections();
                    swipeConsumerView.smoothTopOpen();
                }
            }
//            autoScrollitem = true;
        } else {
            if (recyclerView.getLastVisibleItemPosition() == list.size() - 1) {
                if (smartSwipeRefresh != null) {
                    smartSwipeRefresh.getSwipeConsumer().lockAllDirections();
                    smartSwipeRefresh.startLoadMore();
                }
                if (swipeConsumerView != null) {
                    swipeConsumerView.lockAllDirections();
                    LogUtil.loge("NestedListContainer", " flaView  NestedListContainer ======222222isPullDown" + isPullDown);
                    swipeConsumerView.smoothBottomOpen();
                }
            }

        }
    }


//    private Runnable mResetRunnable = new Runnable() {
//        @Override
//        public void run() {
//            swipeConsumerView.smoothClose();
//            swipeConsumerView.unlockAllDirections();
//        }
//    };


    protected SmartSwipeRefresh.SmartSwipeRefreshDataLoader dataLoader = new SmartSwipeRefresh.SmartSwipeRefreshDataLoader() {
        @Override
        public void onRefresh(final SmartSwipeRefresh ssr) {
            getUITaskDispatcher().delayDispatch(new Runnable() {
                @Override
                public void run() {
                    adapter.refreshData(getData());
                    ssr.finished(true);
                }
            }, 1000);
//            new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
//                @Override
//                public void run() {
//                    adapter.refreshData(getData());
//                    ssr.finished(true);
//                }
//            }, 1000);
        }

        @Override
        public void onLoadMore(final SmartSwipeRefresh ssr) {

            getUITaskDispatcher().delayDispatch(new Runnable() {
                @Override
                public void run() {
                    adapter.addData(getData());
                    ssr.setNoMoreData(true);
                    ssr.finished(true);
                }
            }, 500);
//            new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
//                @Override
//                public void run() {
//                    adapter.addData(getData());
//                    ssr.setNoMoreData(true);
//                    ssr.finished(true);
//                }
//            }, 500);
        }
    };


    protected List<Data> getInitData() {
        return getData();
    }

    protected List<Data> getData() {
        if (names == null) {
            names = getStringArray(ResourceTable.Strarray_demo_names);
            messages = getStringArray(getMessageArray());
        }
        int size = 10;
        List<Data> list = new ArrayList<>(size);
        Data data;
        for (int i = 0; i < size; i++) {
            data = new Data();
            data.id = idMaker.getAndIncrement();
            data.name = names[data.id % names.length];
            data.avatar = AVATARS[data.id % AVATARS.length];
            data.lastMessage = messages[data.id % messages.length];
            list.add(data);
        }
        return list;
    }

    protected int getMessageArray() {
        return ResourceTable.Strarray_demo_messages;
    }


    protected class RecyclerAdapter extends BaseItemProvider {
        List<Data> list;

        RecyclerAdapter(List<Data> list) {
            this.list = list;
        }

        public void refreshData(List<Data> list) {
            this.list = list;
            notifyDataChanged();
        }

        public void addData(List<Data> list) {
            int oldSize = this.list.size();
            this.list.addAll(list);
            notifyDataSetItemRangeInserted(oldSize, list.size());
        }

        public void removeItem(int position) {
            if (position >= 0 && position < list.size()) {
                list.remove(position);
                notifyDataChanged();
            }
        }

        public List<Data> getData() {
            return list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int position, Component convertView, ComponentContainer parent) {
            ViewHolder holder;
//            if (convertView == null) {
                Component child = LayoutScatter.getInstance(BaseRecyclerViewAbility.this).parse(ResourceTable.Layout_layout_item_view, parent, false);
                convertView = child;
                holder = createRecyclerViewHolder(convertView);
                convertView.setTag(holder);
//
//            } else {
//                holder = (ViewHolder) convertView.getTag();
//            }
            if (holder != null) {
                holder.onBindData(list.get(position), position);
            }

            SmartSwipeWrapper swipeWrapper = (SmartSwipeWrapper) holder.contentView;
            swipeWrapper.setOnDirectionLisenter(new SmartSwipeWrapper.OnDirectionLisenter() {
                @Override
                public void onHorizental(float xLast, float curX) {
                    LogUtil.loge("NestedListContainer", "NestedListContainer ======11111");
                    if (Math.abs(xLast - curX) > 20) {
                        handleHorizental(xLast < curX);
                    }

                }

                @Override
                public void onVeltical(float yLast, float curY) {
                    LogUtil.loge("NestedListContainer", "NestedListContainer   ViewHolder======222222");
                    if (Math.abs(yLast - curY) > 20) {
                        handleVetical(yLast < curY, list);
                    }
                }

                @Override
                public void close() {
                    if (swipeConsumerView != null) {
                        LogUtil.loge("NestedListContainer", "smoothClose  smoothClose   ViewHolder======222222");
                        swipeConsumerView.smoothClose();
                    }
                }
            });

            convertView = swipeWrapper;

            LogUtil.loge("NestedListContainer", "NestedListContainer ======" + (convertView.getComponentParent() == null));

            return convertView;
        }

    }

    protected abstract ViewHolder createRecyclerViewHolder(Component view);

    protected class ViewHolder {
        private Text tvName;
        private Text tvLastMessage;
        private Image ivAvatar;
        private Data data;
        private int mPosition;
        public Component contentView;

        public ViewHolder(Component rootView) {
            contentView = rootView;
            if (rootView instanceof ComponentParentHack) {
                ((ComponentParentHack) rootView).setComponentParent(recyclerView);
            }
            tvName = (Text) rootView.findComponentById(ResourceTable.Id_tv_name);
            tvLastMessage = (Text) rootView.findComponentById(ResourceTable.Id_tv_message);
            ivAvatar = (Image) rootView.findComponentById(ResourceTable.Id_iv_avatar);
            rootView.setTag(this);
            ((Component) ivAvatar.getComponentParent()).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (data != null) {
                        Intent intent = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withBundleName(getBundleName())
                                .withAbilityName(ImageViewerAbility.class.getName())
                                .build();
                        intent.setOperation(operation);
                        intent.setParam(ImageViewerAbility.IMAGE_EXTRA, data.avatar);
                        startAbility(intent);
                    }
                }
            });
        }

        public int getPosition() {
            return mPosition;
        }

        protected void onBindData(Data data, int position) {
            this.data = data;
            this.mPosition = position;
            if (data.avatar != 0) {
                ivAvatar.setPixelMap(data.avatar);
            }
            tvName.setText(data.name);
            tvLastMessage.setText(data.lastMessage);
        }
    }


    public static class Data {
        int id;
        String name;
        String lastMessage;
        int avatar;
    }

    static final int[] AVATARS = new int[]{
            ResourceTable.Media_avatar_1,
            ResourceTable.Media_avatar_2,
            ResourceTable.Media_avatar_3,
            ResourceTable.Media_avatar_4,
            ResourceTable.Media_avatar_5,
            ResourceTable.Media_avatar_6,
            ResourceTable.Media_avatar_7,
            ResourceTable.Media_avatar_8,
            ResourceTable.Media_avatar_9,
            ResourceTable.Media_avatar_10,
            ResourceTable.Media_avatar_11,
            ResourceTable.Media_avatar_12,
            ResourceTable.Media_avatar_13,
            ResourceTable.Media_avatar_14,
            ResourceTable.Media_avatar_15,
            ResourceTable.Media_avatar_16,
            ResourceTable.Media_avatar_17,
            ResourceTable.Media_avatar_18,
            ResourceTable.Media_avatar_19,
            ResourceTable.Media_avatar_20
    };
}
